package org.aicfve.asset;

import org.aicfve.config.StorageConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;

@Controller
@RequestMapping(value="/assets")
public class AssetController {

    Logger logger = LoggerFactory.getLogger(AssetController.class);

    @Autowired
    StorageConfig storageConfig;

    @RequestMapping(value = "/**")
    public ResponseEntity download(HttpServletRequest request) {
        logger.debug("{} method {} header {}",this.getClass(),request);

        // get url
        String uri = request.getRequestURI();

        // convert local path

        String local_path = storageConfig.getSavepath() + uri.replaceFirst("^" + storageConfig.getUrlpath(),"");

        // get File
        File download_file = new File(URLDecoder.decode(local_path));
        if(!download_file.exists())
        {
            // 没有找到文件
            return new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }

        long contentLength = download_file.length();

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(download_file);
        } catch (FileNotFoundException e) {
            return new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT);
        }

        // file inputstream
        InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);

        //make httpheader
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment",download_file.getName());
        httpHeaders.setContentLength(contentLength);
        return new ResponseEntity(inputStreamResource,httpHeaders,HttpStatus.CREATED);
    }
}
